package com.kcwl.idea.plugins.base.utils;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

public class KcAesCrypt {
    public static final String bm = "UTF-8";
    private String privateKey;

    public KcAesCrypt(String password) {
        this.privateKey = password;
    }

    public String encrypt(String cleartext) {
        try {
            SecretKeySpec key = new SecretKeySpec(this.privateKey.getBytes("UTF-8"), "AES");
            Cipher cipher = Cipher.getInstance("AES");
            cipher.init(1, key);
            byte[] encryptedData = cipher.doFinal(cleartext.getBytes("UTF-8"));
            return new String(this.parseByte2HexStr(encryptedData));
        } catch (Throwable var5) {

        }
        return "加密失败";
    }

    public String decrypt(String encrypted) {
        try {
            byte[] byteMi = this.parseHexStr2Byte(encrypted);
            SecretKeySpec key = new SecretKeySpec(this.privateKey.getBytes("UTF-8"), "AES");
            Cipher cipher = Cipher.getInstance("AES");
            cipher.init(2, key);
            byte[] decryptedData = cipher.doFinal(byteMi);
            return new String(decryptedData, "UTF-8");
        } catch (Throwable var6) {

        }
        return "解密失败";
    }

    private String parseByte2HexStr(byte[] buf) {
        StringBuilder sb = new StringBuilder();

        for(int i = 0; i < buf.length; ++i) {
            String hex = Integer.toHexString(buf[i] & 255);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }

            sb.append(hex.toUpperCase());
        }

        return sb.toString();
    }

    private byte[] parseHexStr2Byte(String hexStr) {
        if (hexStr.length() < 1) {
            return null;
        } else {
            byte[] result = new byte[hexStr.length() / 2];

            for(int i = 0; i < hexStr.length() / 2; ++i) {
                int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
                int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16);
                result[i] = (byte)(high * 16 + low);
            }

            return result;
        }
    }
}
